package com.chinecredit.cas.action;

import com.chinecredit.cas.domain.UsernamePasswordAndKaptchaCredential;
import com.chinecredit.cas.exception.BadDataException;
import com.chinecredit.cas.exception.NullDataException;
import com.chinecredit.cas.utils.KaptchaUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.jasig.cas.authentication.Credential;
import org.jasig.cas.authentication.RootCasException;
import org.jasig.cas.web.flow.AuthenticationViaFormAction;
import org.jasig.cas.web.support.WebUtils;
import org.springframework.binding.message.MessageBuilder;
import org.springframework.binding.message.MessageContext;
import org.springframework.webflow.execution.RequestContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


public class KaptchaAuthenticationViaFormAction extends AuthenticationViaFormAction {

    /**
     * 校验验证码
     * @param context
     * @param credential
     * @param messageContext
     * @return
     * @throws Exception
     */
    public final String validateKaptcha(final RequestContext context, final Credential credential, final MessageContext messageContext) throws Exception{
        HttpServletRequest request = WebUtils.getHttpServletRequest(context);
        HttpSession session = request.getSession();
        String kaptcha = (String)session.getAttribute(KaptchaUtil.KAPTCHA_KEY);
        session.removeAttribute(KaptchaUtil.KAPTCHA_KEY);

        UsernamePasswordAndKaptchaCredential upc = (UsernamePasswordAndKaptchaCredential) credential;
        String inputKaptcha = upc.getKaptcha();
        if(StringUtils.isEmpty(inputKaptcha) || StringUtils.isEmpty(kaptcha)){
            this.popErrorInstance(new NullDataException(),messageContext);
            return "error";
        }else if(!inputKaptcha.equals(kaptcha)){
            this.popErrorInstance(new BadDataException(),messageContext);
            return "error";
        }

        String username = upc.getUsername();
        String password = upc.getPassword();
        ByteSource salt = ByteSource.Util.bytes(username+password);
        SimpleHash sh = new SimpleHash("MD5", password, salt, 1024);
        upc.setPassword(sh.toString());
        return "success";
    }

    private void popErrorInstance(final RootCasException e,final MessageContext messageContext){
        messageContext.addMessage(new MessageBuilder().error().code(e.getCode()).defaultText(e.getCode()).build());
    }
}
